import math
from queue import PriorityQueue

import pygame

WIDTH = 800
WIN = pygame.display.set_mode((WIDTH, WIDTH))
pygame.display.set_caption("A* pathfinding")

RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
PURPLE = (128, 0, 128)
ORANGE = (255, 165, 0)
GREY = (128, 128, 128)
TURQUOISE = (64, 224, 208)


class Spot:
    def __init__(self, row, col, width, rows_total):
        self.row = row
        self.col = col
        self.x = row * width
        self.y = col * width
        self.color = WHITE
        self.neighbors = []
        self.width = width
        self.rows_total = rows_total

    def get_pos(self):
        return self.row, self.col

    def is_closed(self):
        return self.color == RED

    def is_open(self):
        return self.color == GREEN

    def is_barrier(self):
        return self.color == BLACK

    def is_start(self):
        return self.color == ORANGE

    def is_end(self):
        self.color == TURQUOISE

    def reset(self):
        self.color = WHITE

    def make_start(self):
        self.color = ORANGE

    def make_closed(self):
        self.color = RED

    def make_open(self):
        self.color = GREEN

    def make_barrier(self):
        self.color = BLACK

    def make_end(self):
        self.color = TURQUOISE

    def make_path(self):
        self.color = PURPLE

    def draw(self, win):
        pygame.draw.rect(win, self.color, (self.x, self.y, self.width, self.width))

    def update_neighbors(self, grid):
        self.neighbors = []
        # down
        if self.row < self.rows_total - 1 and not grid[self.row + 1][self.col].is_barrier():
            self.neighbors.append(grid[self.row + 1][self.col])

        if self.row > 0 and not grid[self.row - 1][self.col].is_barrier():  # up
            self.neighbors.append(grid[self.row - 1][self.col])

        # right
        if self.col < self.rows_total - 1 and not grid[self.row][self.col + 1].is_barrier():
            self.neighbors.append(grid[self.row][self.col + 1])

        if self.col > 0 and not grid[self.row][self.col - 1].is_barrier():  # left
            self.neighbors.append(grid[self.row][self.col - 1])

        #down
        if self.judge(self.row + 1, self.col+1) and not grid[self.row + 1][self.col+1].is_barrier():
            self.neighbors.append(grid[self.row + 1][self.col+1])

        # up
        if self.judge(self.row - 1, self.col-1) and not grid[self.row - 1][self.col-1].is_barrier():
            self.neighbors.append(grid[self.row - 1][self.col-1])

        # right
        if self.judge(self.row-1, self.col + 1) and not grid[self.row-1][self.col + 1].is_barrier():
            self.neighbors.append(grid[self.row-1][self.col + 1])

        # left
        if self.judge(self.row+1, self.col - 1) and not grid[self.row+1][self.col - 1].is_barrier():
            self.neighbors.append(grid[self.row+1][self.col - 1])

    def judge(self, x, y):
        return x > 0 and y > 0 and x < self.rows_total and y < self.rows_total

    def __lt__(self, other):
        return False


def h(p1, p2):
    x1, y1 = p1
    x2, y2 = p2
    return abs(x1 - x2) + abs(y1 - y2)


def reconstruct_path(came_from, current, draw):
    while current in came_from:
        current = came_from[current]
        current.make_path()
        draw()


def algorithm(draw, grid, start, end):
    count = 0
    open_set = PriorityQueue()  # 优先级队列
    open_set.put((0, count, start))  # 初始化open表,把头节点加入
    came_from = {}  # 用于最后回溯路,字典
    g_score = {spot: float("inf")for row in grid for spot in row}  # 字典，对每一个坐标步数打分，设初值为无穷
    g_score[start] = 0
    f_score = {spot: float("inf") for row in grid for spot in row}
    f_score[start] = 0+h(start.get_pos(), end.get_pos())  # 字典，对节点打分，激活函数分数+步数分数，设初值为无穷

    open_set_hash = {start}  # 集合，用于判断节点是否在open表

    while not open_set.empty():  # 当open表中有元素，一直遍历
        for event in pygame.event.get():  # 检测点击退出
            if event.type == pygame.QUIT:
                pygame.quit()

        current = open_set.get()[2]  # 从优先级队列获得打分最小的节点，并删除它，再访问它
        open_set_hash.remove(current)  # 从优先级队列移除
        if current == end:  # 当到达目标，跳出循环
            reconstruct_path(came_from, end, draw)  # 重溯整个最短路
            end.make_end()
            return True
        temp_g_score = g_score[current] + 1  # 对将要扩展的节点步数打分加一
        for neighbor in current.neighbors:  # 添加节点
            if temp_g_score < g_score[neighbor]:  # 判断节点是否被添加过，没被添加过初值为无穷
                came_from[neighbor] = current  # 设节点的父节点，用于最后回溯
                g_score[neighbor] = temp_g_score  # 设置节点步数分数
                f_score[neighbor] = temp_g_score + \
                    h(neighbor.get_pos(), end.get_pos())  # 对节点打分
                if neighbor not in open_set_hash:  # 没有在open表中，则添加节点到open表中
                    count += 1
                    # neighbor是一个class,所有节点都是一个class
                    open_set.put((f_score[neighbor], count, neighbor))
                    open_set_hash.add(neighbor)
                    neighbor.make_open()  # 用于画图，节点设为绿色
        # 画图
        draw()
        # 当前节点不是初始节点，变为红色
        if current != start:
            current.make_closed()
    # 假如open表为空还没有找到路径，返回false,表示找不到路径
    return False


def make_grid(rows, width):
    grid = []
    gap = width // rows
    for i in range(rows):
        grid.append([])
        for j in range(rows):
            spot = Spot(i, j, gap, rows)
            grid[i].append(spot)
    return grid


def draw_grid(win, rows, width):
    GAP = width // rows
    for i in range(rows):
        pygame.draw.line(win, GREY, (0, i * GAP), (width, i * GAP))
        for j in range(rows):
            pygame.draw.line(win, GREY, (j * GAP, 0), (j * GAP, width))


def draw(win, grid, rows, width):
    win.fill(WHITE)
    for row in grid:
        for spot in row:
            spot.draw(win)
    draw_grid(win, rows, width)
    pygame.display.update()


def get_clicked_pos(pos, rows, width):
    Gap = width // rows
    y, x = pos

    row = y // Gap
    col = x // Gap
    return row, col


def main(win, width):
    ROWS = 50

    grid = make_grid(ROWS, width)

    start = None
    end = None

    run = True
    started = False
    while run:
        draw(win, grid, ROWS, width)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

            if started:
                continue
            if pygame.mouse.get_pressed()[0]:
                # left
                pos = pygame.mouse.get_pos()
                row, col = get_clicked_pos(pos, ROWS, width)
                spot = grid[row][col]
                if not start and spot != end:
                    start = spot
                    start.make_start()

                elif not end and spot != start:
                    end = spot
                    end.make_end()

                elif spot != end and spot != start:
                    spot.make_barrier()

            elif pygame.mouse.get_pressed()[2]:
                pos = pygame.mouse.get_pos()
                row, col = get_clicked_pos(pos, ROWS, width)
                spot = grid[row][col]
                spot.reset()
                if spot == start:
                    start = None
                if spot == end:
                    end = None

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE and not started:
                    for row in grid:
                        for spot in row:
                            spot.update_neighbors(grid)

                    algorithm(lambda: draw(win, grid, ROWS, width),
                              grid, start, end)

    pygame.quit()


main(WIN, WIDTH)
